using System;
using System.Collections.Generic;
using System.Reflection;
using Cysharp.Threading.Tasks;
using Core.Runtime;

namespace GameLauncher.Runtime
{
    public class EditorModeState : AssemblyLoaderState
    {
        public override async UniTask<StateResult> Execute()
        {
            await UniTask.Yield();
            CollectAssemblies();
            HotFixUI.Release();
            return Launcher.TryLaunchGame(MainLogicAssembly, HotfixAssemblies) ? StateResult.Success() : StateResult.Failure("编辑器模式启动失败");
        }

        private void CollectAssemblies()
        {
            HotfixAssemblies.Clear();

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                CheckMainAssembly(assembly);
                CollectHotUpdateAssemblies(assembly);
            }
        }

        private void CheckMainAssembly(Assembly assembly)
        {
            var expectedName = GameSettings.LogicMainDll;
            if (string.Equals($"{assembly.GetName().Name}.dll", expectedName, StringComparison.Ordinal))
            {
                MainLogicAssembly = assembly;
            }
        }

        private void CollectHotUpdateAssemblies(Assembly assembly)
        {
            var hotUpdateNames = GameSettings.HotUpdateAssemblies;
            var assemblyName = $"{assembly.GetName().Name}.dll";

            if (hotUpdateNames.Contains(assemblyName))
            {
                HotfixAssemblies.Add(assembly);
            }
        }
    }
}